package com.hexiaohe.springboot_vue_app.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hexiaohe.springboot_vue_app.entity.Fruit;
import com.hexiaohe.springboot_vue_app.entity.User;
import com.hexiaohe.springboot_vue_app.service.FruitService;
import com.hexiaohe.springboot_vue_app.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/fruit")
public class FruitController {
    @Autowired
    FruitService fruitService;

    @GetMapping("/getFruitsTable")
    public Result<?> getFruitsTable(@RequestParam(defaultValue = "1")Integer pageNum,
                                    @RequestParam(defaultValue = "10")Integer pageSize){
        Page<Fruit> fruitPage =fruitService.findpage(new Page<>(pageNum,pageSize));
        return Result.success(fruitPage);
    }
    @PostMapping("/addFruit")
    public Result<?>save(@RequestBody Fruit fruit){
        System.out.println(fruit);
        int row = fruitService.addFruit(fruit);
        if (row>0){
            return Result.success();
        }else {
            return Result.error("-1","新增水果失败！");
        }
    }

    @PutMapping("/editFruit")
    public Result<?>update(@RequestBody Fruit fruit){
        int row = fruitService.updateById(fruit);
        if (row>0){
            return Result.success();
        }else {
            return Result.error("-1","水果修改失败");
        }
    }
    @DeleteMapping("/deleteFruitById/{id}")
    public Result<?>deleteFruitById(@PathVariable int id){
        int row =fruitService.deleteFruitById(id);
        try {
            if (row>0){
                return Result.success();
            }else {
                return Result.error("-1","水果删除失败！");
            }
        }
       catch (Exception e){
           return Result.error("-1","水果删除失败！");
       }
    }
    @GetMapping("/getFruitList")
    public Result<?>getFruitList(){
        List<Fruit> fruit= fruitService.getFruitList();
        return Result.success(fruit);
    }
}
